"""
价格利润率变动记录对话框
"""
from PyQt6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel, 
                           QTableWidget, QTableWidgetItem, QHeaderView, 
                           QPushButton, QMessageBox)
from PyQt6.QtCore import Qt, QSize
from PyQt6.QtGui import QColor
from datetime import datetime
import logging

from com.db.profit_rate_price_manager import ProfitRatePriceManager

logger = logging.getLogger(__name__)

class ProfitRatePriceHistoryDialog(QDialog):
    """价格利润率变动记录对话框"""
    
    def __init__(self, goods_id, goods_name=None, parent=None):
        super().__init__(parent)
        self.goods_id = goods_id
        self.goods_name = goods_name
        self.profit_rate_price_manager = ProfitRatePriceManager()
        
        self.setup_ui()
        self.load_data()
    
    def setup_ui(self):
        """初始化UI"""
        self.setWindowTitle("价格利润率变动记录")
        self.setMinimumSize(1200, 600)  # 增加窗口大小以适应更多列
        
        layout = QVBoxLayout(self)
        layout.setContentsMargins(20, 20, 20, 20)
        layout.setSpacing(15)
        
        # 标题
        title_layout = QHBoxLayout()
        title_label = QLabel(f"商品ID: {self.goods_id}")
        title_label.setStyleSheet("font-size: 16px; font-weight: bold;")
        title_layout.addWidget(title_label)
        
        if self.goods_name:
            name_label = QLabel(f"商品名称: {self.goods_name}")
            name_label.setStyleSheet("font-size: 16px; font-weight: bold;")
            title_layout.addWidget(name_label)
        
        title_layout.addStretch()
        layout.addLayout(title_layout)
        
        # 表格
        self.table = QTableWidget()
        # 增加表格列数，包含新增字段
        self.table.setColumnCount(12)  # 增加到12列，包含更多关键信息
        self.table.setHorizontalHeaderLabels([
            "扫货价定价类型", "扫货价", "利润率", "目标售价", 
            "基础扫货价", "常卖价", "普通售价", "调整策略",
            "参考价来源", "推算利润率", "修改类型", "修改时间"
        ])
        
        # 设置表格样式
        self.table.setStyleSheet("""
            QTableWidget {
                border: 1px solid #d9d9d9;
                border-radius: 4px;
                background-color: white;
                gridline-color: #f0f0f0;
            }
            QTableWidget::item {
                padding: 5px;
                border-bottom: 1px solid #f0f0f0;
            }
            QTableWidget::item:selected {
                background-color: #e6f7ff;
                color: black;
            }
            QHeaderView::section {
                background-color: #fafafa;
                padding: 5px;
                border: none;
                border-right: 1px solid #f0f0f0;
                border-bottom: 1px solid #d9d9d9;
                font-weight: bold;
            }
        """)
        
        # 设置表头
        header = self.table.horizontalHeader()
        header.setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
        header.setDefaultAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
        
        layout.addWidget(self.table)
        
        # 底部按钮
        button_layout = QHBoxLayout()
        button_layout.addStretch()
        
        self.close_btn = QPushButton("关闭")
        self.close_btn.setStyleSheet("""
            QPushButton {
                background-color: #1890ff;
                border: none;
                border-radius: 4px;
                color: white;
                padding: 8px 16px;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #40a9ff;
            }
            QPushButton:pressed {
                background-color: #096dd9;
            }
        """)
        self.close_btn.clicked.connect(self.accept)
        button_layout.addWidget(self.close_btn)
        
        layout.addLayout(button_layout)
    
    def load_data(self):
        """加载数据"""
        try:
            # 获取商品的历史利润率和价格变动记录
            records = self.profit_rate_price_manager.get_history_records(self.goods_id, limit=100)
            
            if not records:
                self.table.setRowCount(1)
                no_data_item = QTableWidgetItem("暂无记录")
                no_data_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
                self.table.setSpan(0, 0, 1, 12)  # 合并单元格，注意这里改为12列
                self.table.setItem(0, 0, no_data_item)
                return
            
            # 设置表格行数
            self.table.setRowCount(len(records))
            
            # 填充数据
            for row, record in enumerate(records):
                # 扫货价定价类型
                pricing_type_text = self.get_pricing_type_text(record.get('pricing_type', 1))
                pricing_type_item = QTableWidgetItem(pricing_type_text)
                self.table.setItem(row, 0, pricing_type_item)
                
                # 扫货价
                buy_price_item = QTableWidgetItem(f"{record.get('buy_price', 0):.2f}")
                buy_price_item.setTextAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
                self.table.setItem(row, 1, buy_price_item)
                
                # 利润率
                profit_rate_item = QTableWidgetItem(f"{record.get('profit_rate', 0):.2f}%")
                profit_rate_item.setTextAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
                self.table.setItem(row, 2, profit_rate_item)
                
                # 目标售价
                target_sell_price_item = QTableWidgetItem(f"{record.get('target_sell_price', 0):.2f}")
                target_sell_price_item.setTextAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
                self.table.setItem(row, 3, target_sell_price_item)
                
                # 基础扫货价（新增）
                base_price = record.get('base_snipe_price')
                base_price_text = f"{base_price:.2f}" if base_price is not None else "-"
                base_price_item = QTableWidgetItem(base_price_text)
                base_price_item.setTextAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
                self.table.setItem(row, 4, base_price_item)
                
                # 常卖价（新增）
                common_price = record.get('common_sell_price')
                common_price_text = f"{common_price:.2f}" if common_price is not None else "-"
                common_price_item = QTableWidgetItem(common_price_text)
                common_price_item.setTextAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
                self.table.setItem(row, 5, common_price_item)
                
                # 普通售价（新增）
                normal_price = record.get('normal_price')
                normal_price_text = f"{normal_price:.2f}" if normal_price is not None else "-"
                normal_price_item = QTableWidgetItem(normal_price_text)
                normal_price_item.setTextAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
                self.table.setItem(row, 6, normal_price_item)
                
                # 调整策略（新增）
                adjustment_strategy = record.get('adjustment_strategy', '-')
                self.table.setItem(row, 7, QTableWidgetItem(adjustment_strategy))
                
                # 参考价来源（新增）
                reference_source = record.get('reference_price_source', '-')
                self.table.setItem(row, 8, QTableWidgetItem(reference_source))
                
                # 推算利润率（新增）
                estimated_profit = record.get('estimated_profit_rate')
                if estimated_profit is not None:
                    estimated_profit_text = f"{estimated_profit:.2f}%"
                else:
                    estimated_profit_text = "-"
                estimated_profit_item = QTableWidgetItem(estimated_profit_text)
                estimated_profit_item.setTextAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
                self.table.setItem(row, 9, estimated_profit_item)
                
                # 修改类型
                modify_type_text = self.get_modify_type_text(record.get('modify_type', 1))
                modify_type_item = QTableWidgetItem(modify_type_text)
                # 根据修改类型设置不同的颜色
                if record.get('modify_type') == 1:  # 自动调整
                    modify_type_item.setForeground(QColor("#1890ff"))  # 蓝色
                elif record.get('modify_type') == 2:  # 人为调整
                    modify_type_item.setForeground(QColor("#52c41a"))  # 绿色
                self.table.setItem(row, 10, modify_type_item)
                
                # 修改时间
                update_time = record.get('update_time')
                if update_time:
                    if isinstance(update_time, str):
                        try:
                            update_time = datetime.strptime(update_time, "%Y-%m-%d %H:%M:%S")
                        except ValueError:
                            pass
                    update_time_text = update_time.strftime("%Y-%m-%d %H:%M:%S") if isinstance(update_time, datetime) else str(update_time)
                else:
                    update_time_text = "-"
                self.table.setItem(row, 11, QTableWidgetItem(update_time_text))
        
        except Exception as e:
            logger.error(f"加载价格利润率变动记录失败: {str(e)}")
            QMessageBox.warning(self, "错误", f"加载数据失败: {str(e)}")
    
    def get_pricing_type_text(self, pricing_type):
        """获取扫货价定价类型文本"""
        pricing_types = {
            0: "按固定价",
            1: "按动态利润率",
            2: "按固定利润率"
        }
        return pricing_types.get(pricing_type, f"未知类型({pricing_type})")
    
    def get_modify_type_text(self, modify_type):
        """获取修改类型文本"""
        modify_types = {
            1: "自动调整",
            2: "人为调整"
        }
        return modify_types.get(modify_type, f"未知类型({modify_type})")
